package com.artist.controller;

import com.artist.entity.Product;
import com.artist.service.ProductService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Api(tags =  "图片上传测试")
@Controller
public class ProductController {
    @Autowired
    private ProductService productService;
    @GetMapping("/image")
    public String testImage(){
        return "imgtest";
    }
    @GetMapping("/list")
    public String listImage(Model model) {
        List<Product> list = productService.list();
        model.addAttribute("list", list);
        System.out.println(list);
        return "list";
    }

    @PostMapping("/addProduct")
    public String fileUpload(MultipartFile file, Product product, ModelMap map) throws IOException {
        /**
         * 上传图片
         */
        //图片上传成功后，将图片的地址写到数据库
        String filePath = "http://120.78.219.91/image";//保存图片的路径
        //获取原始图片的拓展名
        String originalFilename = file.getOriginalFilename();
        //新的文件名字
        String newFileName = UUID.randomUUID() + originalFilename;
        //封装上传文件位置的全路径
        File targetFile = new File(filePath, newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);
        product.setPimage(newFileName);

        /**
         * 保存商品
         */
        productService.save(product);
        return "redirect:/list";
    }
}
